package com.example.juejincheck.utils;

import com.example.juejincheck.domain.FeidianConfig;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author yangkun
 * @description
 * @date 2022年12月13日 9:24
 */
public class ToJSONUtils {
     int x;
    public static String toJSON(Object obj){
        Class<?> aClass = obj.getClass();
        StringBuilder sb = new StringBuilder("{");
        for (int i = 0; i < aClass.getDeclaredFields().length; i++) {
            Field declaredField = aClass.getDeclaredFields()[i];
            System.out.println();
            String name = declaredField.getName();
            try {
                Method declaredMethod = aClass.getDeclaredMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
                Object invoke = declaredMethod.invoke(obj);
                sb.append(declaredField.getName()).append(":");
                if(invoke != null){
                    if(declaredMethod.getReturnType().equals(String.class)){
                        sb.append("\"").append(invoke).append("\"");
                    }else{
                        sb.append(invoke);
                    }
                }else{
                    sb.append(invoke);
                }
                if(i != aClass.getDeclaredFields().length-1){
                    sb.append(",");
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return sb.append("}").toString();
    }

    public static void main(String[] args) throws MalformedURLException {
        FeidianConfig feidianConfig = new FeidianConfig();
        feidianConfig.setContent("测试");
        feidianConfig.setId(222);
        System.out.println(ToJSONUtils.toJSON(feidianConfig));
    }
}
